package cn.wenzy.aurora.framework.converter;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.Filter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import com.google.common.collect.Lists;
import org.springframework.http.MediaType;


public class FastJson2HttpMessageConverter extends FastJsonHttpMessageConverter {

    public FastJson2HttpMessageConverter(Filter... filters) {
        super();
        initSupportedMediaTypes();
        initFastJsonConfig(filters);
    }


    private void initSupportedMediaTypes() {
        setSupportedMediaTypes(Lists.newArrayList(
                MediaType.APPLICATION_JSON,
                MediaType.APPLICATION_JSON_UTF8,
                MediaType.APPLICATION_ATOM_XML,
                MediaType.APPLICATION_FORM_URLENCODED,
                MediaType.APPLICATION_OCTET_STREAM,
                MediaType.APPLICATION_PDF,
                MediaType.APPLICATION_RSS_XML,
                MediaType.APPLICATION_XHTML_XML,
                MediaType.APPLICATION_XML,
                MediaType.IMAGE_GIF,
                MediaType.IMAGE_JPEG,
                MediaType.IMAGE_PNG,
                MediaType.TEXT_EVENT_STREAM,
                MediaType.TEXT_HTML,
                MediaType.TEXT_MARKDOWN,
                MediaType.TEXT_PLAIN,
                MediaType.TEXT_XML
        ));
    }

    private void initFastJsonConfig(Filter... filters) {
        FastJsonConfig config = getFastJsonConfig();
        // 修改配置返回内容的过滤
        config.setWriterFeatures(
                JSONWriter.Feature.PrettyFormat, // 格式化输出
                JSONWriter.Feature.WriteMapNullValue, // 是否输出值为null的字段,默认为false
                JSONWriter.Feature.WriteNullStringAsEmpty, // 字符类型字段如果为null,输出为"",而非null
                JSONWriter.Feature.ReferenceDetection // 消除对同一对象循环引用的问题，默认为false（如果不配置会有$ref对象重复引用问题）
        );
        if (ArrayUtil.isNotEmpty(filters)) {
            config.setWriterFilters(ArrayUtil.append(config.getWriterFilters(), filters));
        }
    }
}
